package sz.szsmk.citizencard.ui.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothGatt;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;


import com.chenenyu.router.annotation.Route;

import java.util.ArrayList;
import java.util.List;

import sz.szsmk.citizencard.R;
import sz.szsmk.citizencard.dialog.ConnectRequestTipsDialog;
import sz.szsmk.citizencard.ui.adapter.DeviceAdapter;
import sz.szsmk.citizencard.ui.base.AppManager;
import sz.szsmk.citizencard.ui.base.SuperActivity;

/**
 * Copyright (c)2018
 * author: zdh
 * created on: 2018/6/29 13:21
 * description:智能充电宝
 */
@Route("battery")
public class SearchDeviceActivity extends SuperActivity {

    private LinearLayout btnBack;
    private TextView textTitle;
    private View btnRefresh;
    private ListView lv;
    private DeviceAdapter deviceAdapter;

    private static final int REQUEST_CODE_OPEN_GPS = 1;
    private static final int REQUEST_CODE_PERMISSION_LOCATION = 2;
    private static final int REQUEST_ENABLE_BT = 3;
    private ConnectRequestTipsDialog connectRequestTipsDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        bleBusiness = BleBusiness.getInstance(getApplicationContext());
        setContentView(R.layout.battery_activity);

        findViewId();
        initData();
        setListener();
        checkPermissions();
    }
    public void showLoadDialog() {
        if (null == connectRequestTipsDialog) {
            connectRequestTipsDialog = new ConnectRequestTipsDialog();
            Bundle bundle = new Bundle();
            bundle.putString("title","正在连接中...");
            connectRequestTipsDialog.setArguments(bundle);
//            progressDialog = new CustomProgressDialog(this);
//            progressDialog.show();
        }

        android.app.FragmentTransaction ft = getFragmentManager().beginTransaction();
        ft.add(connectRequestTipsDialog, this.getClass().getSimpleName());
        ft.commitAllowingStateLoss();
    }

    public void dismissLoadingDialog() {
        if (null != connectRequestTipsDialog) {
            connectRequestTipsDialog.dismissAllowingStateLoss();
            connectRequestTipsDialog = null;
        }
//        if (null != progressDialog) {
//            progressDialog.dismiss();
//            progressDialog = null;
//        }
    }
    @Override
    protected void onResume() {
        super.onResume();
        showConnectedDevice();
    }
    private void showConnectedDevice() {
        deviceAdapter.notifyDataSetChanged();
    }

    @Override
    protected void findViewId() {
        btnBack = (LinearLayout) findViewById(R.id.menu_back);
        textTitle = (TextView) findViewById(R.id.text_title);
        btnRefresh = findViewById(R.id.image_menu_right);
        lv = (ListView) findViewById(R.id.lv);
    }

    @Override
    protected void initData() {
        textTitle.setText("设备列表");
//        text_right.setText("搜索");
        deviceAdapter = new DeviceAdapter(SearchDeviceActivity.this);
        lv.setAdapter(deviceAdapter);


//        if (hasPermission()) {
//            scan();
//        }
    }



    @Override
    protected void setListener() {
        btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AppManager.getAppManager().finishActivity(SearchDeviceActivity.this);
            }
        });
        btnRefresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    checkPermissions();
            }
        });
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {


            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    @Override
    protected void onPause() {
        super.onPause();
    }








    private void checkPermissions() {
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (!bluetoothAdapter.isEnabled()) {
            new AlertDialog.Builder(this)
                    .setTitle(R.string.notifyTitle)
                    .setMessage(R.string.blueNotifyMsg)
                    .setNegativeButton(R.string.cancel,
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    finish();
                                }
                            })
                    .setPositiveButton(R.string.openblue,
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    bluetoothAdapter.enable();
                                    checkPermissions();
                                }
                            })

                    .setCancelable(false)
                    .show();




            return;
        }

        String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION};
        List<String> permissionDeniedList = new ArrayList<>();
        for (String permission : permissions) {
            int permissionCheck = ContextCompat.checkSelfPermission(this, permission);
            if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
                onPermissionGranted(permission);
            } else {
                permissionDeniedList.add(permission);
            }
        }
        if (!permissionDeniedList.isEmpty()) {
            String[] deniedPermissions = permissionDeniedList.toArray(new String[permissionDeniedList.size()]);
            ActivityCompat.requestPermissions(this, deniedPermissions, REQUEST_CODE_PERMISSION_LOCATION);
        }
    }

    private void onPermissionGranted(String permission) {
        switch (permission) {
            case Manifest.permission.ACCESS_FINE_LOCATION:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !checkGPSIsOpen()) {
                    new AlertDialog.Builder(this)
                            .setTitle(R.string.notifyTitle)
                            .setMessage(R.string.gpsNotifyMsg)
                            .setNegativeButton(R.string.cancel,
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            finish();
                                        }
                                    })
                            .setPositiveButton(R.string.setting,
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                            startActivityForResult(intent, REQUEST_CODE_OPEN_GPS);
                                        }
                                    })

                            .setCancelable(false)
                            .show();
                } else {
//                    scanAndConnect();
                }
                break;
        }
    }

    private boolean checkGPSIsOpen() {
        LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        if (locationManager == null)
            return false;
        return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_OPEN_GPS) {
            if (checkGPSIsOpen()) {
//                scanAndConnect();
            }
        }
        if(requestCode==REQUEST_ENABLE_BT){
          checkPermissions();
        }
    }

}
